/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-01-31 09:19:58
 * @LastEditors: zhangjx
 * @LastEditTime: 2023-05-25 14:13:33
 */
const KEY_NAME = 'apld-xningxiang-'

/**
 * 判断是否为空
 */
export function validatenull(val: Boolean | Number) {
	if (typeof val === 'boolean') {
		return false
	}
	if (typeof val === 'number') {
		return false
	}
	if (val instanceof Array) {
		if (val.length === 0) return true
	} else if (val instanceof Object) {
		if (JSON.stringify(val) === '{}') return true
	} else {
		if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') return true
		return false
	}
	return false
}

export const setStore = (name: string, content: string | Object, type: string = 'session') => {
	name = KEY_NAME + name
	const obj = {
		dataType: typeof content,
		content: content,
		type: type,
		datetime: new Date().getTime(),
	}
	if (type) {
		window.sessionStorage.setItem(name, JSON.stringify(obj))
	} else {
		window.localStorage.setItem(name, JSON.stringify(obj))
	}
}

/**
 * 获取localStorage
 */

export const getStore = (name: string, debug: Boolean = false) => {
	name = KEY_NAME + name
	let obj: any = {}
	let content
	obj = window.sessionStorage.getItem(name)
	if (validatenull(obj)) obj = window.localStorage.getItem(name)
	if (validatenull(obj)) return
	try {
		obj = JSON.parse(obj)
	} catch (e) {
		return obj
	}
	if (debug) {
		return obj
	}
	if (obj.dataType === 'string') {
		content = obj.content
	} else if (obj.dataType === 'number') {
		content = Number(obj.content)
	} else if (obj.dataType === 'object') {
		content = obj.content
	}
	return content
}
/**
 * 删除localStorage
 */
export const removeStore = (name: string, type?: string) => {
	name = KEY_NAME + name
	if (!type) {
		window.sessionStorage.removeItem(name)
	} else {
		window.localStorage.removeItem(name)
	}
}
/**
 * 清空全部localStorage
 */
export const clearStore = (type: string) => {
	if (type) {
		window.sessionStorage.clear()
	} else {
		window.localStorage.clear()
	}
}
